package com.cci.kangdao.service.impl;

import com.cci.kangdao.common.type.GradeType;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.ServiceInformationService;
import com.cci.kangdao.utilTool.*;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service("serviceInformationService")
public class ServiceInformationServiceImpl implements ServiceInformationService {
	private Logger log = Logger.getLogger(this.getClass().getName());

	@Autowired
	private ServiceInformationDao serviceInformationDao;
	@Autowired
	private RedisClientUtils redisClientUtils;
	@Resource
	private PropertiesUtils propertiesUtils;
	@Autowired
	private TypicalCaseDao typicalCaseDao;
	@Resource
	private ServiceStationDao serviceStationDao;
	@Resource
	private FaultCodeTDao faultCodeTDao;
	@Resource
	private LoginDao loginDao;
	@Resource
	private UserTokenTMapper userTokenTMapper;
	@Resource
	private EngineMsgDao engineMsgDao;
	@Resource
	private CDSEngineInfoTDao cdsEngineInfoTDao;
	@Resource
	private LoginServiceImpl loginService;
	@Resource
	private WAactiveFaultcodeMapper wAactiveFaultcodeMapper;


	private static final String KFZ = "kfz";



	/**
	 * App用户获取服务手册接口
	 */
	@Override
	public ModelAndView getServiceHandbook(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();

			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));

			/**
			 * 1、查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);// 解密userid
			UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);

			/**
			 * 2、查询所有的SMN： 康明斯游客查看全部； Jv只能查看自己企业的机型，因此可查询对应自己企业的机型对应SMN；
			 * Dealer用户：根据Dealer用户所属服务站查询服务站对应的机型
			 */
			List<EngineTypeT> engineTypeList = null;
			//授权机型的id
			String engineTypeID="";
			/*if(userT.getIsType() == 0){
				obj.put("status", 0);
				obj.put("msg", "");
				obj.put("handbooks", new JSONArray());
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}else if (userT.getIsType() == 1) {
				map.put("userType", 1);
				engineTypeList = serviceStationDao.findEngineTypeList(null);
			} else if (userT.getIsType() == 6) { // dealer用户组
				map.put("userType", 6);
				map.put("serviceStationID", "" + userT.getServiceStationID());
				engineTypeList = serviceStationDao.findEngineTypeListByStation(""+userT.getServiceStationID());
			} else {
				map.put("userType", userT.getIsType());
				map.put("companyID", "" + userT.getCompanyId());
				engineTypeList = serviceStationDao.findEngineTypeList(""+userT.getCompanyId());
			}*/
			map.put("userType", 1);
			engineTypeList = serviceStationDao.findEngineTypeList(null);
			if (engineTypeList != null) {
//				for (EngineTypeT engineTypeT : engineTypeList) {
//					engineTypeID+=""+engineTypeT.getId()+",";
//				}
//				if(engineTypeID.endsWith(",")){
//					engineTypeID=engineTypeID.substring(0,engineTypeID.length()-1);
//				}
				List<Long> collect = engineTypeList.stream().map(EngineTypeT::getId).collect(Collectors.toList());
				map.put("engineTypeIDs", collect);
			}
			PageHelper.startPage(page, pagesize);
			// 查询所有的sSMN
			List<SMNT> smnList = serviceInformationDao.getAllSMN(map);
			// 查询所有的故障手册、维修手册、技术公告
			List<HandbookT> handbookList = null;
			List<CircuitDiagramT> circuitDiagramList = null;
			/**
			 * 遍历所有的SMN的id
			 */
//			String smnID = "";
//			for (SMNT smnT : smnList) {
//				smnID += smnT.getID() + ",";
//			}
//			if (smnID.endsWith(",")) {
//				smnID = smnID.substring(0, smnID.length() - 1);
//			}
			if (CollectionUtils.isNotEmpty(smnList)) {
				List<Long> collect = smnList.stream().map(SMNT::getID).collect(Collectors.toList());
				map.put("smnID", collect);
				// 查询所有的故障手册、维修手册、技术公告
				handbookList = serviceInformationDao.getAllBookHandDatas(map);
				circuitDiagramList = serviceInformationDao.getAllCircuitDiagramDatas(map);
			}

			/**
			 * 放入到map<SMNID,handbookT>
			 */
			Map<String, HandbookT> handbookMap = new HashMap<String, HandbookT>();
			Map<String, CircuitDiagramT> circuitDiagramMap = new HashMap<String, CircuitDiagramT>();

			if (handbookList != null) {
				for (HandbookT bean : handbookList) {
					// 0故障码诊断手册，1维护手册，2技术公告
					// 0type1 1type1 2type1 0type2 2type2
					handbookMap.put(bean.getType() + "type" + bean.getSMNId(), bean);
				}
				handbookList.clear();// 垃圾回收
				handbookList = null;
			}
			if (circuitDiagramList != null) {
				for (CircuitDiagramT bean : circuitDiagramList) {
					circuitDiagramMap.put("" + bean.getSMNId(), bean);
				}
				circuitDiagramList.clear();// 垃圾回收
				circuitDiagramList = null;
			}
			//PageHelper.startPage(page, pagesize);
			/**
			 * 3、将查询结果返回客户端
			 */
			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			for (SMNT smnT : smnList) {
				/**
				 * "id": "DESSED", "SMNname": "0012", "diagnosis": 0,
				 * "servicebook": 1, "notice": 2, "circuitdiagramId":"ESDES",
				 * "circuitdiagram": "http://222x.pdf", "circuitdiagramisLogo":0
				 */
				content = new JSONObject();
				content.put("SMNname", smnT.getSMNname());
				// 0故障码诊断手册，1维护手册，2技术公告
				if (handbookMap.get("0type" + smnT.getID()) != null) {
					content.put("id", AESTool.encryptString("" + handbookMap.get("0type" + smnT.getID()).getSMNId()));
					content.put("diagnosis", 0);
				}
				if (handbookMap.get("1type" + smnT.getID()) != null) {
					content.put("id", AESTool.encryptString("" + handbookMap.get("1type" + smnT.getID()).getSMNId()));
					content.put("servicebook", 1);
				}
				if (handbookMap.get("2type" + smnT.getID()) != null) {
					content.put("id", AESTool.encryptString("" + handbookMap.get("2type" + smnT.getID()).getSMNId()));
					content.put("notice", 2);
				}
				// 电路图
				CircuitDiagramT circuitDiagramT = circuitDiagramMap.get("" + smnT.getID());
				if (circuitDiagramT != null) {
					content.put("circuitdiagramId", AESTool.encryptString("" + circuitDiagramT.getID()));
					content.put("circuitdiagram", circuitDiagramT.getFileUrl());
					content.put("circuitdiagramisLogo", circuitDiagramT.getIsLogo());
				}
				jsonArray.put(content);
			}

			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("handbooks", jsonArray);
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * App用户搜索服务信息接口
	 */
	@Override
	public ModelAndView searchServiceHandbook(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();

			/**
			 * 判断参数
			 */
			if (map.get("searchTxt") == null) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			if (map.get("searchTxt") != null && !map.get("searchTxt").toString().equals("")) {
				map.put("searchTxt", "%" + map.get("searchTxt") + "%");
			}

			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));

			/**
			 * 
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);// 解密userid
			UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);

			/**
			 * 1、查询所有的SMN： 康明斯查看全部； Jv只能查看自己企业的机型，因此可查询对应自己企业的机型对应SMN；
			 * Dealer用户：根据Dealer用户所属服务站查询服务站对应的机型;
			 * 普通用户没有权限；
			 */
			/*if(userT.getIsType() == 0){
				obj.put("status", 0);
				obj.put("msg", "");
				obj.put("handbooks", new JSONArray());
				obj.put("typicalCase", new JSONArray());
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}else if (userT.getIsType() == 1) {
				map.put("userType", 1);
			} else if (userT.getIsType() == 6) { // dealer用户组
				map.put("userType", 6);
				map.put("serviceStationID", "" + userT.getServiceStationID());
			} else {
				map.put("userType", userT.getIsType());
				map.put("companyID", "" + userT.getCompanyId());
			}*/
			map.put("userType", 1);
			/*
			 * "id": "DESSED", "SMNname": "0012", "type": 0,
			 * "circuitdiagramId":"ESDES", "circuitdiagram": "http://222x.pdf",
			 * "circuitdiagramisLogo":0
			 */
			/**
			 * emissionStandard technologyMap 技术路线 排放标准 and
			 * (CHARINDEX(#{emissionStandard}, c.EmissionStandard)>0 or
			 * CHARINDEX(#{emissionStandard}, c.EmissionStandard))
			 */
			String emissionStandard = "";
			if (map.get("emissionStandard") != null) {
				emissionStandard = "" + map.get("emissionStandard");
				if (!emissionStandard.equals("")) {
//					String[] split = emissionStandard.split(",");
//					emissionStandard = " and (";
//					for (String emission : split) {
//						emissionStandard += " CHARINDEX('" + emission + "', c.EmissionStandard)>0 or";
//					}
//					if (emissionStandard.endsWith("or")) {
//						emissionStandard = emissionStandard.substring(0, emissionStandard.length() - 2);
//					}
//					emissionStandard += ")";
					String[] split = emissionStandard.split(",");
					ArrayList<String> arrayList = new ArrayList<String>(split.length);
					Collections.addAll(arrayList, split);
					map.put("emissionStandard", arrayList);
				} else {
					map.remove("emissionStandard");
				}
			}


			String technologyMap = "";
			if (map.get("technologyMap") != null) {
				technologyMap = "" + map.get("technologyMap");
				if (!technologyMap.equals("")) {
					String[] split = technologyMap.split(",");
//					technologyMap = " and (";
//					for (String emission : split) {
//						technologyMap += " CHARINDEX('" + emission + "', c.TechnologyMap)>0 or";
//					}
//					if (technologyMap.endsWith("or")) {
//						technologyMap = technologyMap.substring(0, technologyMap.length() -2);
//					}
//					technologyMap += ")";
					ArrayList<String> arrayList = new ArrayList<String>(split.length);
					Collections.addAll(arrayList, split);
					map.put("technologyMap", arrayList);
				} else {
					map.remove("technologyMap");
				}
			}


			obj.put("status", 0);
			obj.put("msg", "");
			PageHelper.startPage(page, pagesize);
			/**
			 * 搜索smn
			 */
			List<SMNT> searchAllSMNList = serviceInformationDao.getSearchAllSMN(map);
			/**
			 * 搜索smn电路图
			 */
			List<CircuitDiagramT> searchAllCircuitDiagramList = serviceInformationDao.getSearchAllCircuitDiagram(map);
			JSONArray jsonArray1 = new JSONArray();
			JSONObject content1 = null;
			if (searchAllSMNList != null) {
				for (SMNT smnt : searchAllSMNList) {
					content1 = new JSONObject();
					if (smnt.getHandBookType() != null) {
						content1.put("id", AESTool.encryptString(smnt.getID().toString()));
						content1.put("SMNname", smnt.getSMNname());
						content1.put("type", smnt.getHandBookType());
						jsonArray1.put(content1);
					}
				}
			}
			if (searchAllCircuitDiagramList != null) {
				for (CircuitDiagramT circuitDiagramT : searchAllCircuitDiagramList) {
					content1 = new JSONObject();
					content1.put("id", AESTool.encryptString(circuitDiagramT.getSMNId().toString()));
					content1.put("SMNname", circuitDiagramT.getSMNname());
					content1.put("circuitdiagramId", AESTool.encryptString(circuitDiagramT.getID().toString()));
					content1.put("circuitdiagram", circuitDiagramT.getFileUrl());
					content1.put("circuitdiagramisLogo", circuitDiagramT.getIsLogo());
					jsonArray1.put(content1);
				}
			}
			obj.put("handbooks", jsonArray1);

			JSONArray jsonArray = new JSONArray();
			JSONObject content = null;
			// 查询典型案例

			List<String> engineTypeIDsList = StringToool.getStringList(MapUtils.getString(map, "engineTypeIDs"), ",");
			if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(engineTypeIDsList)) {
				map.put("engineTypeIDs", engineTypeIDsList);
			} else {
				map.remove("engineTypeIDs");
			}
			List<TypicalCaseT> typicalCaseList = typicalCaseDao.getTypicalCase(map);
			if (typicalCaseList != null) {
				for (TypicalCaseT typicalCaseT : typicalCaseList) {
					content = new JSONObject();
					content.put("caseName", typicalCaseT.getCaseName());
					content.put("fileUrl", typicalCaseT.getFileUrl());
					content.put("isLogo", typicalCaseT.getIsLogo());
					jsonArray.put(content);
				}
			}
			obj.put("typicalCase", jsonArray);
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * App用户获取服务手册目录接口
	 */
	@Override
	public ModelAndView getHandbookDir(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();
			// handbookId是不是空
			if (map.get("handbookId") == null || map.get("handbookId").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			// type 是不是null
			if (map.get("type") == null || map.get("type").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
			// handbookid 解密
			String handbookId = AESTool.decryptString(map.get("handbookId").toString());
			map.put("handbookId", handbookId);
			obj.put("status", 0);
			obj.put("msg", "");
			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			/*
			 * bookDirs": [{ "id": "DESSED", "bookDirname": "引言" }]
			 */
			PageHelper.startPage(page, pagesize);
			// 查询目录以及目录ID
			List<ServiceBookDirT> handbookDirList = serviceInformationDao.getHandbookDir(map);
			if (handbookDirList != null) {
				for (ServiceBookDirT serviceBookDirT : handbookDirList) {
					content = new JSONObject();
					content.put("id", AESTool.encryptString(serviceBookDirT.getID().toString()));
					content.put("bookDirname", serviceBookDirT.getBookDirname());
					jsonArray.put(content);
				}
			}
			obj.put("bookDirs", jsonArray);
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * App用户获取服务手册详细接口
	 */
	@Override
	public ModelAndView getHandbookDetail(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 判断参数
			 */

			if (map.get("handbookId") == null || map.get("handbookId").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));

			// handbookid 解密
			String handbookId = AESTool.decryptString(map.get("handbookId").toString());
			map.put("handbookId", handbookId);
			// 返回参数
			obj.put("status", 0);
			obj.put("msg", "");
			JSONObject content;
			JSONArray jsonArray = new JSONArray();		
			/**
			 * 查询手册信息
			 */
			HandbookT handbookT = serviceInformationDao.getHandbookById(Long.valueOf(handbookId));
			if (handbookT != null) {
				obj.put("isLogo", handbookT.getIsLogo());
			}
			/*
			 * "status": 0, "msg": "", "isLogo": 0, "handbooks": [{ "id":
			 * "ESEBS", "FileName": "引言", "FileUrl": "http://22x.pdf" }]
			 */
			// 查询电路图详细手册的章节名字，上传路径
			PageHelper.startPage(page, pagesize);
			List<HandbookDetailT> handbookDetail = serviceInformationDao.getHandbookDetail(map);

			if (handbookDetail != null) {
				for (HandbookDetailT handbookDetailT : handbookDetail) {
					content = new JSONObject();
					content.put("id", AESTool.encryptString(handbookDetailT.getID().toString()));
					content.put("FileName", handbookDetailT.getFileName());
					content.put("FileUrl", handbookDetailT.getFileUrl());
					jsonArray.put(content);
				}
			}
			obj.put("handbooks", jsonArray);
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * App用户上传手册阅读次数接口
	 */
	@Override
	public ModelAndView uploadHandTolNum(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();

			/**
			 * 判断接受的参数 fileId type
			 */
			if (map.get("fileId") == null || map.get("fileId").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			if (map.get("type") == null || map.get("type").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			// fileId 解密
			String fileId = AESTool.decryptString(map.get("fileId").toString());
			map.put("fileId", fileId);
			/**
			 * 查看type类型是多少 手册类型，0诊断手册，1维护手册，3电路图
			 */
			if (map.get("type").toString().equals("0") || map.get("type").toString().equals("1")) {
				map.put("handBookType", 0);
			} else if (map.get("type").toString().equals("3")) {// 电路图
				map.put("handBookType", 3);
			} else if(map.get("type").toString().equals("10")) {
				map.put("handBookType", 10);
			}

			/**
			 * 去更新阅读次数
			 */
			//2.1.0需求   因为技术公告单独新建了两个表   所以这块更新阅读次数换新逻辑     其他的还是原逻辑
			int result = 0 ;
			if(map.get("type").toString().equals("2")){  //2代表技术公告
				result = serviceInformationDao.updateTechServiceBookNum(Long.parseLong(fileId));
			}else{
				result = serviceInformationDao.uploadHandTolNum(map);
			}

			if (result > 0) {
				obj.put("status", 0);
				obj.put("msg", "");
			}else{
				obj.put("status", -99);
				obj.put("msg", "未知错误");
			}

			// 返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * App用户搜索代码故障接口(app在1.0.5版本之前的都走这个方法)
	 */
	@Override
	public ModelAndView searchFaultCode(Map<String, Object> map) {

		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();

			// 判断传递的参数
			if (map.get("searchTxt") == null || map.get("searchTxt").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));

			/**
			 * 判断参数type 查询类型：0表示SPN/FMI，1标示故障代码，默认0
			 */
			String type = "0";
			if (map.get("type") != null) {
				type = "" + map.get("type");
			}

			/**
			 * 1、查询用户信息
			 */
			String userid = request.getHeader("userid");			
			
			/**
			 * 默认情况下是0 ，或者type是0先分割参数search 得到spn和fmi
			 * 根据这俩得到faultcode,在去smn跟颜色，描述等
			 * 
			 */
			FaultCodeT faultCode = null;
			String searchTxt = ",";
			if (type.equals("0")) {
				/**
				 * 默认情况下是0把查询参数分割,根据spn,fmi区查询FaultCode
				 */
				String[] split = map.get("searchTxt").toString().split("@");
				map.put("spn", split[0]);
				map.put("fmi", split[1]);
				List<FaultCodeT> faultCodeList = serviceInformationDao.getFaultCode(map);
				if (faultCodeList == null || faultCodeList.size() == 0) {
					obj.put("status", 0);
					obj.put("msg", "");
					obj.put("SMSes", new JSONArray());
					// 返回客户
					ParameterTool.writeResponse(response, obj.toString());
					obj = null;
					return null;
				}
				faultCode = faultCodeList.get(0);
				for(FaultCodeT bean : faultCodeList){
					searchTxt += bean.getFaultCode()+",";
				}
				//and CHARINDEX(','+a.FaultCode+',', ',1597,1388,1116,343,111,')>0 防止出现597也在查询结果里面
				map.put("searchTxt", " and CHARINDEX(','+a.FaultCode+',', '"+searchTxt+"')>0");
			} else {				
				/**
				 *  必须先查询根据故障代码查询故障的 故障颜色 故障描述
				 *  然后再拼接故障代码
				 */
				List<FaultCodeT> faultCodeList = serviceInformationDao.getSearchFaultColorAndDescribe(map);
				if (faultCodeList == null || faultCodeList.size() == 0) {
					obj.put("status", 0);
					obj.put("msg", "");
					obj.put("SMSes", new JSONArray());
					// 返回客户
					ParameterTool.writeResponse(response, obj.toString());
					obj = null;
					return null;
				}
				faultCode = faultCodeList.get(0);
				
				/**
				 * 然后再拼接故障代码
				 */
				if (map.get("searchTxt") != null || !map.get("searchTxt").toString().equals("")) {
					searchTxt = map.get("searchTxt").toString();
					map.put("searchTxt",  searchTxt.replaceAll("'", "’"));
				}
			}
			/*
			 * {
				"status": 0,
				"msg": "",
				"faultColor": "颜色",
				"description": "描述",
				"SMSes": [{
					"id": "DESSED",
					"SMNname": "0012",
					"fileName": "引言",
					"fileUrl": "http://22x.pdf",
					"isLogo": 0
				}]
			}
			 */
			obj.put("status", 0);
			obj.put("msg", "");
			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			obj.put("faultCode", faultCode.getFaultCode());
			obj.put("faultColor", faultCode.getFaultColor());
			obj.put("description", faultCode.getDescription());
			obj.put("severityLevel", faultCode.getSeverityLevel());
			obj.put("faultReason", StringUtils.isBlank(faultCode.getFaultReason())? "": faultCode.getFaultReason());
			obj.put("SPNFMI", faultCode.getSPN()+"|"+faultCode.getFMI());
			obj.put("operSuggest", StringUtils.isBlank(faultCode.getOperSuggest())? "": faultCode.getOperSuggest());
			/**
			 * 如果游客身份只查询故障代码，不查询smn
			 */
			if(userid == null){
				obj.put("SMSes", jsonArray);
				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			/**
			 * 2、故障代码搜索： 康明斯查看全部； Jv只能查看自己企业的机型，因此可查询对应自己企业的机型对应SMN；
			 * Dealer用户：根据Dealer用户所属服务站查询服务站对应的机型；客户只搜索故障代码，不搜索SMN;
			 */
			if(userid !=null){
				userid = AESTool.decryptString(userid);// 解密userid
				UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
				if(null == userT) {
					userT = loginDao.getUserByid(userid);
					int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
					redisClientUtils.setObject("userT"+userT.getId(), userT, redisCacheTime);
				}
				if(userT.getIsType() == 0){
					obj.put("status", 0);
					obj.put("msg", "");
					obj.put("SMSes", jsonArray);
					// 返回客户
					ParameterTool.writeResponse(response, obj.toString());
					obj = null;
					return null;
				}else if (userT.getIsType() == 1) {
					map.put("userType", 1);
				} else if (userT.getIsType() == 6) { // dealer用户组
					map.put("userType", 6);
					map.put("serviceStationID", "" + userT.getServiceStationID());
				} else {
					map.put("userType", userT.getIsType());
					map.put("companyID", "" + userT.getCompanyId());
				}
			}
			// 查询故障代码下的smn
			List<SMNT> faultCodeSMNList = serviceInformationDao.getFaultCodeSMN(map);
			if (faultCodeSMNList != null) {
				for (SMNT smnt : faultCodeSMNList) {
					content = new JSONObject();
					content.put("id", AESTool.encryptString(smnt.getHandbookDetailID().toString()));
					content.put("SMNname", smnt.getSMNname());
					content.put("fileName", smnt.getFileName());
					content.put("fileUrl", smnt.getFileUrl());
					content.put("isLogo", smnt.getIsLogo());
					content.put("bookDirname", smnt.getBookDirname());
					jsonArray.put(content);
				}
			}
			obj.put("SMSes", jsonArray);
			// 返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;

		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}
	
	
	
	/**
	 * App用户搜索代码故障接口(app在1.0.5版本之后的都走这个方法)
	 */
	@Override
	public ModelAndView searchFaultCode2(Map<String, Object> map) {

		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();

			// 判断传递的参数,当前端传递的参数为空时，返回给前端状态和信息，方法结束
			if (map.get("searchTxt") == null || map.get("searchTxt").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			//设置分页信息
			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));

			/**
			 * 判断参数type 查询类型：0表示SPN/FMI，1标示故障代码，默认0
			 */
			String type = "0";
			if (map.get("type") != null) {
				type = "" + map.get("type");
			}

			/**
			 * 1、查询用户信息
			 */
			String userid = request.getHeader("userid");
			
			/**
			 * 默认情况下是0 ，或者type是0先分割参数search 得到spn和fmi
			 * 根据这俩得到faultcode,在去smn跟颜色，描述等
			 * 
			 */
			FaultCodeT faultCode = null;
			//创建faultCodeList集合，用来保存返给前端faultCodeList所有的数据
			List<FaultCodeT> faultCodeList = null;
			String searchTxt = ",";
			if (type.equals("0")) {
				/**
				 * 默认情况下是0把查询参数分割,根据spn,fmi区查询FaultCode
				 */
				String[] split = map.get("searchTxt").toString().split("@");
				map.put("spn", split[0]);
				map.put("fmi", split[1]);
				faultCodeList = serviceInformationDao.getFaultCode(map);
				if (faultCodeList == null || faultCodeList.size() == 0) {
					obj.put("status", 0);
					obj.put("msg", "");
					obj.put("faultCodeList",new JSONArray());
					// 返回客户
					ParameterTool.writeResponse(response, obj.toString());
					obj = null;
					return null;
				}
				for(FaultCodeT bean : faultCodeList){
					searchTxt += bean.getFaultCode()+",";
				}
				//and CHARINDEX(','+a.FaultCode+',', ',1597,1388,1116,343,111,')>0 防止出现597也在查询结果里面
				map.put("searchTxt", " and CHARINDEX(','+a.FaultCode+',', '"+searchTxt+"')>0");
			} else {				
				/**
				 *  必须先查询根据故障代码查询故障的 故障颜色 故障描述
				 *  然后再拼接故障代码
				 */
				String faultCodeTxt = map.get("searchTxt").toString(); //获取需要查询的故障码
				//如果该故障码前缀有0开头的都去了
				while (faultCodeTxt.startsWith("0")){
					faultCodeTxt = faultCodeTxt.substring(1);
				}
				map.put("searchTxt",faultCodeTxt);
				faultCodeList = serviceInformationDao.getSearchFaultColorAndDescribe(map);
				if (faultCodeList == null || faultCodeList.size() == 0) {
					obj.put("status", 0);
					obj.put("msg", "");
					obj.put("faultCodeList",new JSONArray());
					// 返回客户
					ParameterTool.writeResponse(response, obj.toString());
					obj = null;
					return null;
				}
				/**
				 * 然后再拼接故障代码
				 */
				if (map.get("searchTxt") != null || !map.get("searchTxt").toString().equals("")) {
					searchTxt = map.get("searchTxt").toString();
					map.put("searchTxt",  searchTxt.replaceAll("'", "’"));
				}
			}
			obj.put("status", 0);
			obj.put("msg", "");
			JSONArray jsonArray = new JSONArray();
			/**
			 * 如果游客身份只查询故障代码，不查询smn
			 */
            if (StringUtils.isEmpty(userid)) {
				JSONArray json = new JSONArray();
				if(CollectionUtils.isNotEmpty(faultCodeList)){
					for(FaultCodeT a : faultCodeList){
		                JSONObject jo = new JSONObject();
		                jo.put("ID", a.getID());
		                jo.put("faultCode", a.getFaultCode());
		                jo.put("SPNFMI", a.getSPN()+"|"+a.getFMI());
		                jo.put("faultColor", a.getFaultColor());

						//先根据故障码去FaultCode_T表查看有没有对应的故障描述
						//若FaultCode_T没有故障描述，去FaultCodeCummins_T查询，先获取FaultCodeCummins_T中AlgorithmDescription字段
						// 若FaultCodeCummins_T中AlgorithmDescription没有值，则获取FaultCodeCummins_T中CumminsDescription字段
						String faultCodeDescription = a.getDescription();
						if(StringUtils.isEmpty(faultCodeDescription)){
							Map<String,Object> faultCodeCumminsTMap = faultCodeTDao.getFaultCodeCumminsTByFaultCode(a.getFaultCode());  //查询FaultCodeCummins_T表
							if(MapUtils.isNotEmpty(faultCodeCumminsTMap)){
								if(!"".equals(MapUtil.getMapValue(faultCodeCumminsTMap,"AlgorithmDescription"))){
									faultCodeDescription = MapUtil.getMapValue(faultCodeCumminsTMap,"AlgorithmDescription");
								}else{
									faultCodeDescription = MapUtil.getMapValue(faultCodeCumminsTMap,"CumminsDescription");
								}
							}
						}

		                jo.put("description", faultCodeDescription);
		                jo.put("advise", a.getAdvise());
		                jo.put("remark", a.getRemark());
		                jo.put("flag", a.getFlag());
		                jo.put("systime", a.getSystime());
		                jo.put("severityLevel", a.getSeverityLevel());
		                jo.put("faultReason", a.getFaultReason());
		                jo.put("operSuggest", a.getOperSuggest());
		                json.put(jo);
		            }
				}
				obj.put("faultCodeList",json);
				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			/**
			 * 2、故障代码搜索： 康明斯查看全部； Jv只能查看自己企业的机型，因此可查询对应自己企业的机型对应SMN；
			 * Dealer用户：根据Dealer用户所属服务站查询服务站对应的机型；客户只搜索故障代码，不搜索SMN;
			 */
            if (StringUtils.isNotEmpty(userid)) {
				userid = AESTool.decryptString(userid);// 解密userid
				UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
				if(null == userT) {
					userT = loginDao.getUserByid(userid);
					if(userT != null){   //数据库查出来用户不为空    把相关信息保存redis中
						int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
						redisClientUtils.setObject("userT"+userT.getId(), userT, redisCacheTime);
					}else{   //如果数据库查出来也是空的    则该用户只能看到游客角色看到的内容
						userT = new UserT();
						userT.setIsType(0);
					}

				}

				//1 康明斯,3 JV,4 OEM,5 SSOEM,6	Dealer,0 Engine Customer
				//用户，oem，ssoem不查询smn数据  ,其他用户组类型查看所有smn数据
				if(userT.getIsType() == 0 || userT.getIsType() == 4 || userT.getIsType() == 5){
					JSONArray json = new JSONArray();
					if(CollectionUtils.isNotEmpty(faultCodeList)){
						for(FaultCodeT a : faultCodeList){
							JSONObject jo = new JSONObject();
							jo.put("ID", a.getID());
							jo.put("faultCode", a.getFaultCode());
							jo.put("SPNFMI", a.getSPN()+"|"+a.getFMI());
							jo.put("faultColor", a.getFaultColor());

							//先根据故障码去FaultCode_T表查看有没有对应的故障描述
							//若FaultCode_T没有故障描述，去FaultCodeCummins_T查询，先获取FaultCodeCummins_T中AlgorithmDescription字段
							// 若FaultCodeCummins_T中AlgorithmDescription没有值，则获取FaultCodeCummins_T中CumminsDescription字段
							String faultCodeDescription = a.getDescription();
							if(StringUtils.isEmpty(faultCodeDescription)){
								Map<String,Object> faultCodeCumminsTMap = faultCodeTDao.getFaultCodeCumminsTByFaultCode(a.getFaultCode());  //查询FaultCodeCummins_T表
								if(MapUtils.isNotEmpty(faultCodeCumminsTMap)){
									if(!"".equals(MapUtil.getMapValue(faultCodeCumminsTMap,"AlgorithmDescription"))){
										faultCodeDescription = MapUtil.getMapValue(faultCodeCumminsTMap,"AlgorithmDescription");
									}else{
										faultCodeDescription = MapUtil.getMapValue(faultCodeCumminsTMap,"CumminsDescription");
									}
								}
							}
							jo.put("description", faultCodeDescription);
							jo.put("advise", a.getAdvise());
							jo.put("remark", a.getRemark());
							jo.put("flag", a.getFlag());
							jo.put("systime", a.getSystime());
							jo.put("severityLevel", a.getSeverityLevel());
							jo.put("faultReason", a.getFaultReason());
							jo.put("operSuggest", a.getOperSuggest());
							json.put(jo);
						}
					}
					obj.put("faultCodeList",json);
					// 返回客户
					ParameterTool.writeResponse(response, obj.toString());
					obj = null;
					return null;
				} else {
					map.put("userType", userT.getIsType());
					map.put("serviceStationID", "" + userT.getServiceStationID());
					map.put("companyID", "" + userT.getCompanyId());
				}
			}
			// 查询故障代码下的smn
			List<SMNT> faultCodeSMNList = serviceInformationDao.getFaultCodeSMN(map);
			//返给手机端所有查询到的数据
			JSONArray json = new JSONArray();
			if(CollectionUtils.isNotEmpty(faultCodeList)){
				for(FaultCodeT a : faultCodeList){
	                JSONObject jo = new JSONObject();
	                jo.put("ID", a.getID());
	                jo.put("faultCode", a.getFaultCode());
	                jo.put("SPNFMI", a.getSPN()+"|"+a.getFMI());
	                jo.put("faultColor", a.getFaultColor());
					//先根据故障码去FaultCode_T表查看有没有对应的故障描述
					//若FaultCode_T没有故障描述，去FaultCodeCummins_T查询，先获取FaultCodeCummins_T中AlgorithmDescription字段
					// 若FaultCodeCummins_T中AlgorithmDescription没有值，则获取FaultCodeCummins_T中CumminsDescription字段
					String faultCodeDescription = a.getDescription();
					if(StringUtils.isEmpty(faultCodeDescription)){
						Map<String,Object> faultCodeCumminsTMap = faultCodeTDao.getFaultCodeCumminsTByFaultCode(a.getFaultCode());  //查询FaultCodeCummins_T表
						if(null != faultCodeCumminsTMap && faultCodeCumminsTMap.size() >0){
							if(!"".equals(MapUtil.getMapValue(faultCodeCumminsTMap,"AlgorithmDescription"))){
								faultCodeDescription = MapUtil.getMapValue(faultCodeCumminsTMap,"AlgorithmDescription");
							}else{
								faultCodeDescription = MapUtil.getMapValue(faultCodeCumminsTMap,"CumminsDescription");
							}
						}
					}
	                jo.put("description", faultCodeDescription);
	                jo.put("advise", a.getAdvise());
	                jo.put("remark", a.getRemark());
	                jo.put("flag", a.getFlag());
	                jo.put("systime", a.getSystime());
	                jo.put("severityLevel", a.getSeverityLevel());
	                jo.put("faultReason", a.getFaultReason());
	                jo.put("operSuggest", a.getOperSuggest());
	                if (faultCodeSMNList != null) {
	                	JSONArray contentArray = new JSONArray();
	    				for (SMNT smnt : faultCodeSMNList) {
	    					if(smnt.getFaultCode() != null) {
	    						if(smnt.getFaultCode().equals(a.getFaultCode())) {
	    							JSONObject content = new JSONObject();
	        						content.put("id", AESTool.encryptString(smnt.getHandbookDetailID().toString()));
	            					content.put("SMNname", smnt.getSMNname());
	            					content.put("fileName", smnt.getFileName());
	            					content.put("fileUrl", smnt.getFileUrl());
	            					content.put("isLogo", smnt.getIsLogo());
	            					content.put("bookDirname", smnt.getBookDirname());
	            					contentArray.put(content);
	        					}
	    					}
	    				}
	    				jo.put("SMSes", contentArray);
	    			}
	                json.put(jo);
	            }
			}else {
				if (faultCodeSMNList != null) {
                	JSONArray contentArray = new JSONArray();
    				for (SMNT smnt : faultCodeSMNList) {
    					if(smnt.getFaultCode() != null) {
    						JSONObject content = new JSONObject();
    						content.put("id", AESTool.encryptString(smnt.getHandbookDetailID().toString()));
        					content.put("SMNname", smnt.getSMNname());
        					content.put("fileName", smnt.getFileName());
        					content.put("fileUrl", smnt.getFileUrl());
        					content.put("isLogo", smnt.getIsLogo());
        					content.put("bookDirname", smnt.getBookDirname());
        					contentArray.put(content);	
    					}
    				}
    				obj.put("SMSes", contentArray);
    			}
			}
			obj.put("faultCodeList", json);
			// 返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;

		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * App用户查询服务首页接口
	 */
	@Override
	public ModelAndView serviceIndex(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();

			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = 5;
			if (map.get("pagesize") != null && !map.get("pagesize").toString().equals("")) {
				pagesize = Integer.parseInt(map.get("pagesize").toString());
			}

			/**
			 * 
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);// 解密userid
			UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
			/**
			 * 1、查询所有的SMN： 康明斯游客查看全部； Jv只能查看自己企业的机型，因此可查询对应自己企业的机型对应SMN；
			 * Dealer用户：根据Dealer用户所属服务站查询服务站对应的机型；普通用户没有权限
			 */

			if(userT.getIsType() == 0){
				obj.put("status", 0);
				obj.put("msg", "");
				obj.put("handbooks", new JSONArray());
				obj.put("books", new JSONArray());
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}else if (userT.getIsType() == 1) {
				map.put("userType", 1);
			} else if (userT.getIsType() == 6) { // dealer用户组
				map.put("userType", 6);
				map.put("serviceStationID", "" + userT.getServiceStationID());
			} else {
				map.put("userType", userT.getIsType());
				map.put("companyID", "" + userT.getCompanyId());
			}
			
			/**
			 * 二期放开权限，任意渠道都可以查看
			 */
			//map.put("userType", 1);
			
			
			obj.put("status", 0);
			obj.put("msg", "");
			// 查询SMN
			map.put("currentTime", LocalTimeUtil.getRealCurrentTime());
			PageHelper.startPage(page, pagesize);
			List<SMNT> searchAllSMNList = serviceInformationDao.getServiceHomeAllSMN(map);
			JSONArray jsonArray1 = new JSONArray();
			JSONObject content;
			/**
			 * type跟电路图是二选一 如果有type,底下没有电路图 如果有电路图没有type
			 * 手册类型，0诊断手册，1维护手册，2公告，3电路图
			 */
			if (searchAllSMNList != null) {
				for (SMNT smnt : searchAllSMNList) {
					content = new JSONObject();
					if (smnt.getHandBookType() < 3) {
						content.put("id", AESTool.encryptString(smnt.getID().toString()));
						content.put("SMNname", smnt.getSMNname());
						content.put("type", smnt.getHandBookType());
						content.put("systime",
								PublicTool.dateTimeChangeChina(smnt.getSystime().toString().substring(0, 19)));
						if(smnt.getHandBookType() == 2){   //技术公告
							content.put("circuitdiagramId", AESTool.encryptString(smnt.getHandBookID().toString()));
							content.put("fileName", StringUtils.isBlank(smnt.getFileName())? "": smnt.getFileName());
							content.put("circuitdiagram", smnt.getFileUrl());
							content.put("circuitdiagramisLogo", smnt.getIsLogo());
						}
						jsonArray1.put(content);
					} else {
						content.put("id", AESTool.encryptString(smnt.getID().toString()));
						content.put("SMNname", smnt.getSMNname());
						content.put("type", 3);
						content.put("circuitdiagramId", AESTool.encryptString(smnt.getHandBookID().toString()));
						content.put("fileName", StringUtils.isBlank(smnt.getFileName())? "": smnt.getFileName());
						content.put("circuitdiagram", smnt.getFileUrl());
						content.put("circuitdiagramisLogo", smnt.getIsLogo());
						content.put("systime",
								PublicTool.dateTimeChangeChina(smnt.getSystime().toString().substring(0, 19)));
						jsonArray1.put(content);
					}
				}
			}
			obj.put("handbooks", jsonArray1);

			JSONArray jsonArray = new JSONArray();
			/**
			 * 查询最新资料信息
			 */
			PageHelper.startPage(page, pagesize);
			List<SMNT> searchAllSMNList1 = serviceInformationDao.getServiceHomeAllSMNByTolnum(map);
			if (searchAllSMNList1 != null) {
				for (SMNT smnt : searchAllSMNList1) {
					/**
					 * "id": "DESSED", "fileName": "ISG2.6无法启动", "fileUrl":
					 * "http://222x.pdf", "isLogo": 0, "systime": "2018-03-20
					 * 12:12:23"
					 */
					content = new JSONObject();
					content.put("id", AESTool.encryptString(smnt.getID().toString()));
					content.put("SMNname", smnt.getSMNname());
					content.put("fileName", smnt.getFileName());
					content.put("fileUrl", smnt.getFileUrl());
					content.put("type", smnt.getHandBookType());
					content.put("isLogo", smnt.getIsLogo());
					content.put("bookDirname", StringUtils.isBlank(smnt.getBookDirname())? "": smnt.getBookDirname());
					content.put("systime",
							PublicTool.dateTimeChangeChina(smnt.getSystime().toString().substring(0, 19)));
					jsonArray.put(content);
				}
			}
			obj.put("books", jsonArray);
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * App用户症状树接口
	 */
	@Override
	public ModelAndView faultCodeTree(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();

			// 判断传递的参数
			if (map.get("searchTxt") == null) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			/**
			 * 
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);// 解密userid
			UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
			if (map.get("searchTxt") != null) {
				map.put("searchTxt", "%" + map.get("searchTxt") + "%");
			}
			/**
			 * 1、查询所有的SMN： 康明斯游客查看全部； Jv只能查看自己企业的机型，因此可查询对应自己企业的机型对应SMN；
			 * Dealer用户：根据Dealer用户所属服务站查询服务站对应的机型；普通用户没有权限
			 */
			List<EngineTypeT> engineTypeList = null;
			//授权机型的id
			String engineTypeIDs="";
			if(userT.getIsType() == 0){
				obj.put("status", 0);
				obj.put("msg", "");
				obj.put("SMSes", new JSONArray());
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}else  if (userT.getIsType() == 1) {
				map.put("userType", 1);
				engineTypeList = serviceStationDao.findEngineTypeList(null);
			} else if (userT.getIsType() == 6) { // dealer用户组
				map.put("userType", 6);
				map.put("serviceStationID", "" + userT.getServiceStationID());
				engineTypeList = serviceStationDao.findEngineTypeListByStation("" + userT.getServiceStationID());
			} else {
				map.put("userType", userT.getIsType());
				map.put("companyID", "" + userT.getCompanyId());
				engineTypeList = serviceStationDao.findEngineTypeList("" + userT.getCompanyId());
			}
			if (engineTypeList != null) {
				for (EngineTypeT engineTypeT : engineTypeList) {
					engineTypeIDs += "" + engineTypeT.getId() + ",";
				}
				if (engineTypeIDs.endsWith(",")) {
					engineTypeIDs = engineTypeIDs.substring(0, engineTypeIDs.length() - 1);
				}
				List<Long> engineTypeIds = engineTypeList.stream().map(EngineTypeT::getId).collect(Collectors.toList());
				map.put("engineTypeIDs", engineTypeIds);
			}
			/**
			 * 查询出目录中带TS的ID
			 */
			String serviceBookDirID = "";
			List<ServiceBookDirT> serviceBookDirDatasList = serviceInformationDao.getServiceBookDir_TDatas();
//			if (serviceBookDir_TDatasList.size() == 1) {
//				serviceBookDirID = " =" + serviceBookDir_TDatasList.get(0).getID().toString();
//			} else if (serviceBookDir_TDatasList.size() > 1) {
//				for (ServiceBookDirT serviceBookDirT : serviceBookDir_TDatasList) {
//					serviceBookDirID += serviceBookDirT.getID() + ",";
//					}
//					if(serviceBookDirID.endsWith(",")){
//						serviceBookDirID =" in ("+serviceBookDirID.substring(0, serviceBookDirID.length()-1)+")";
//					}
//				}
			if (com.cci.kangdao.utilTool.CollectionUtils.isNotEmpty(serviceBookDirDatasList)) {
				List<String> collect = serviceBookDirDatasList.stream().map(e -> {
					return e.getID().toString();
				}).collect(Collectors.toList());
				map.put("serviceBookDirID", collect);
			}
			obj.put("status", 0);
			obj.put("msg", "");
			JSONArray jsonArray1 = new JSONArray();
			JSONObject content;
			JSONArray jsonArray;
			JSONObject content1;
			List<SMNT> faultCodeTree = serviceInformationDao.getFaultCodeTree(map);
			if (faultCodeTree == null || faultCodeTree.size() == 0) {
				obj.put("SMSes", jsonArray1);
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			// "SMSes": [{
			// "SMNname": "0012",
			// "isLogo": 0,
			// "faultCodes": [{
			// "id": "DESSED",
			// "fileName": "引言",
			// "fileUrl": "http://22x.pdf"
			// }, {
			// "id": "DESSED",
			// "fileName": "引言",
			// "fileUrl": "http://22x.pdf"
			// }]
			// }]

			content = new JSONObject();
			jsonArray = new JSONArray();
			for (SMNT smnt : faultCodeTree) {
				if (!content.has("SMNname")) {
					content.put("SMNname", smnt.getSMNname());
					content.put("isLogo", smnt.getIsLogo());
				}
				if (content.get("SMNname") != null && !smnt.getSMNname().equals(content.getString("SMNname"))) {
					content.put("faultCodes", jsonArray);
					jsonArray1.put(content);
					content = new JSONObject();
					jsonArray = new JSONArray();
					if (!content.has("SMNname")) {
						content.put("SMNname", smnt.getSMNname());
						content.put("isLogo", smnt.getIsLogo());
					}
				}
				content1 = new JSONObject();
				content1.put("id", AESTool.encryptString(smnt.getHandbookDetailID().toString()));
				content1.put("fileName", smnt.getFileName());
				content1.put("fileUrl", smnt.getFileUrl());
				content1.put("bookDirname", StringUtils.isBlank(smnt.getBookDirname())? "": smnt.getBookDirname());
				jsonArray.put(content1);
			}
			content.put("faultCodes", jsonArray);
			jsonArray1.put(content);
			obj.put("SMSes", jsonArray1);
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

    @Override
    public ModelAndView getFCCodeBySPNAndFMI(Map<String, Object> map) {
		JSONObject mapvo = new JSONObject();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
		try {
			if (null == map.get("params")) {
				mapvo.put("status", -5);
				mapvo.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				// 返回客户
				ParameterTool.writeResponse(response, mapvo.toString());
				return null;
			}
			net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(map.get("params"));
			List<Map<String, Object>> listvo = new ArrayList<>();
			Map<String, Object> mapVo;
			for (Object faultCodeT : jsonArray) {
				net.sf.json.JSONObject jsonObjectDto = net.sf.json.JSONObject.fromObject(faultCodeT);
				String spn = (String) jsonObjectDto.get("SPN");
				String fmi = (String) jsonObjectDto.get("FMI");
				String esn = (String) jsonObjectDto.get("ESN");
				mapVo = new HashedMap<>();
				mapVo.put("ESN", esn);
				mapVo.put("FMI", fmi);
				mapVo.put("SPN", spn);
				mapVo.put("list", new ArrayList<>());
				if (StringUtils.isNotBlank(spn) && StringUtils.isNotBlank(fmi) && StringUtils.isNotBlank(esn)) {
					List<FaultCodeT> fcCodeBySPNAndFMI = faultCodeTDao.getFCCodeBySPNAndFMI(spn, fmi, esn);
					if (com.cci.kangdao.utilTool.CollectionUtils.isEmpty(fcCodeBySPNAndFMI)) {
						Map<String, Object> engineMsgMap = engineMsgDao.getSMNByESN(esn);
						if (null != engineMsgMap) {
//							String smnByESN = this.getSMNByESN(esn);
//							if (StringUtils.isNotBlank(smnByESN)) {
							List<Map<String, Object>> list = cdsEngineInfoTDao.selectList(esn);
							if (com.cci.kangdao.utilTool.CollectionUtils.isEmpty(list)) {
								String smnByESN = this.getSMNByESN(esn);
								if (StringUtils.isNotBlank(smnByESN)) {
									CDSEngineInfoT cdsEngineInfoT = new CDSEngineInfoT();
									cdsEngineInfoT.setSmn(smnByESN);
									cdsEngineInfoT.setEsn(esn);
									cdsEngineInfoT.setCreator(-1L);
									cdsEngineInfoT.setVersion(0);
									cdsEngineInfoT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
									cdsEngineInfoT.setMakeName(MapUtil.getMapValue(engineMsgMap, "MakeName"));
									cdsEngineInfoT.setModelName(MapUtil.getMapValue(engineMsgMap, "ModelName"));
									cdsEngineInfoT.setApplication(MapUtil.getMapValue(engineMsgMap, "Application"));
									cdsEngineInfoT.setWarrantyStartDate(MapUtil.getMapValue(engineMsgMap, "WarrantyStartDate"));
									cdsEngineInfoT.setFlag(0);
									int insert = cdsEngineInfoTDao.insert(cdsEngineInfoT);
									fcCodeBySPNAndFMI = faultCodeTDao.getFCCodeBySPNAndFMI(spn, fmi, esn);
									mapVo.put("list", this.getGradefcCodeBySPNAndFMI(fcCodeBySPNAndFMI));
								}
							}
//							}
						}
						listvo.add(mapVo);
					} else {
						mapVo.put("list", this.getGradefcCodeBySPNAndFMI(fcCodeBySPNAndFMI));
						listvo.add(mapVo);
					}
				} else {
					listvo.add(mapVo);
				}
			}
			//将维修建议 赋值 查询cip的接口
			this.getProposal(listvo);
			mapvo.put("status", 0);
			mapvo.put("msg", "成功");
            mapvo.put("data", listvo);
			ParameterTool.writeResponse(response, mapvo.toString());
			return null;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			String msg = "{\"status\": -99,\"msg\": \"未知错误\"}";
			ParameterTool.writeResponse(response, msg);
		}
        return null;
    }

	//	通过cip获取  维修建议
	private void getProposal(List<Map<String, Object>> listvo) {
		Map<String, Object> param;

		for (Map<String, Object> map : listvo) {
			String urlByProposal = PropertiesUtil.getProperties("projectconfig.properties", "cip.urlByProposal");
			String appkey = PropertiesUtil.getProperties("projectconfig.properties", "cip.appkey");

			ArrayList<Map<String, Object>> list = (ArrayList) map.get("list");
			if (CollectionUtils.isNotEmpty(list)) {
				for (Map<String, Object> objectMap : list) {
					String faultCode = (String) objectMap.get("faultCode");
					if (StringUtils.isBlank(faultCode)) {
						continue;
					}
					//是否在清单内
					boolean contains = this.isContains(faultCode);
					if (!contains) {
						objectMap.put("advise", "请联系服务站获取详情");
						continue;
					}
                    if (objectMap.containsKey("operSuggest") && StringUtils.isNotBlank((String) objectMap.get("operSuggest"))) {
                        objectMap.put("advise", objectMap.get("operSuggest"));
						continue;
					}
					//			封装参数
					param = new HashMap<>();
					param.put("esn", map.get("ESN"));
					param.put("faultCode", faultCode);
					BasicHeader basicHeader = new BasicHeader("Content-Type", "application/json");
					BasicHeader appkeyHeader = new BasicHeader("app-key", appkey);
					//访问cip的接口
					String response = HttpUtils.postJson(urlByProposal, com.alibaba.fastjson.JSONObject.toJSONString(param), new ResponseHandler<String>() {
						@Override
						public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
							if (response.getStatusLine().getStatusCode() == 200) {
								HttpEntity httpEntity = response.getEntity();
								return EntityUtils.toString(httpEntity, "UTF-8");
							}
							return null;
						}
					}, basicHeader, appkeyHeader);
					if (StringUtils.isNotEmpty(response)) {
						com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
						if (jsonObject.containsKey("code") && (int) jsonObject.get("code") == 0) {
							if (jsonObject.containsKey("data")) {
								String string = com.alibaba.fastjson.JSONObject.toJSONString(jsonObject.get("data"));
								if (StringUtils.isNotBlank(string)) {
									com.alibaba.fastjson.JSONObject dataObject = com.alibaba.fastjson.JSONObject.parseObject(string);
									String advice = (String) dataObject.get("advice");
									objectMap.put("advise", advice);
								}
							}
						}

					}
				}
			}

		}
	}

	//是否在清单内；
	public boolean isContains(String faultCode) {
		boolean flag = false;
		List<WAactiveFaultcode> list = wAactiveFaultcodeMapper.getList();
		if (com.cci.kangdao.utilTool.CollectionUtils.isNotEmpty(list)) {
			flag = list.stream().anyMatch(e -> faultCode.equals(e.getFaultcode()));
		}
		return flag;
	}

	public List<net.sf.json.JSONObject> getGradefcCodeBySPNAndFMI(List<FaultCodeT> fcCodeBySPNAndFMI) {

        //String 红色：立即停机维护
        //淡黄色：立即采取行动
        //白色/维修保养：稍后采取行动
        //无：提醒注意
		net.sf.json.JSONObject jsonObject;
		List<net.sf.json.JSONObject> list = new ArrayList<>();
		for (FaultCodeT faultCodeT : fcCodeBySPNAndFMI) {
			jsonObject = net.sf.json.JSONObject.fromObject(faultCodeT);
			jsonObject.put("gradeType", this.getGrade(faultCodeT));
			list.add(jsonObject);
		}
		return list;
    }

	public int getGrade(FaultCodeT faultCodeT) {
		String faultColor = faultCodeT.getFaultColor();
		if (GradeType.TYPE9.getMessage().contains(faultColor)) {
			return GradeType.TYPE9.getCode();
		} else if (GradeType.TYPE6.getMessage().contains(faultColor)) {
			return GradeType.TYPE6.getCode();
		} else if (GradeType.TYPE3.getMessage().contains(faultColor)) {
			return GradeType.TYPE3.getCode();
		} else if (GradeType.TYPE1.getMessage().contains(faultColor)) {
			return GradeType.TYPE1.getCode();
		} else {
			return GradeType.TYPE1.getCode();
		}
	}

	@Override
	public ModelAndView getSMN(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		String smn = getSMNByESN((String) map.get("esn"));
		ParameterTool.writeResponse(response, smn);
		return null;
	}

	//根据esn调用美国的接口
	public String getSMNByESN(String esn) {
		Map<String, String> param = new HashMap<>(1);
		param.put("esn", esn);

		Header Cache = new BasicHeader("Cache-Control", "no-cache");
		Header Accept = new BasicHeader("Accept", "*/*");
		Header encoding = new BasicHeader("Accept-Encoding", "gzip, deflate, br");
		Header Connection = new BasicHeader("Connection", "keep-alive");

		Header authAuthorization = new BasicHeader("Authorization", "Bearer " + getseThreadbyUserId());
		Header authUsername = new BasicHeader("Username", "NA");
		Header authApplication = new BasicHeader("Application-ID", "NA");
		Header authDistribution = new BasicHeader("Distribution-Channel", "NA");
		Header authSP = new BasicHeader("SP-Code", "NA");

		String getSmnUrl = PropertiesUtil.getProperties("projectconfig.properties", "aws.siebel.getSmn");
		String responseEntity = HttpUtils.get(getSmnUrl, param, new ResponseHandler<String>() {
			@Override
			public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
				if (response.getStatusLine().getStatusCode() == 200) {
					HttpEntity httpEntity = response.getEntity();
					return EntityUtils.toString(httpEntity);
				} else if (response.getStatusLine().getStatusCode() == 403) {
					//刷新token
					String s = loginService.remoteRefreshToken("1");
					Header authAuthorizationTwo = new BasicHeader("Authorization", "Bearer " + getseThreadbyUserId());
					String responseEntity = HttpUtils.get(getSmnUrl, param, new ResponseHandler<String>() {
						@Override
						public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
							if (response.getStatusLine().getStatusCode() == 200) {
								HttpEntity httpEntity = response.getEntity();
								return EntityUtils.toString(httpEntity);
							} else {
								log.error("异常，response：" + response);
							}
							return null;
						}
					}, authAuthorizationTwo, authUsername, authApplication, authDistribution, authSP, Accept, Connection, encoding, Cache);
					return responseEntity;
				} else {
					log.error("异常，response：" + response);
				}
				return null;
			}
		}, authAuthorization, authUsername, authApplication, authDistribution, authSP, Accept, Connection, encoding, Cache);
		if (StringUtils.isBlank(responseEntity)) {
			return null;
		}
		com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(responseEntity);
		AwsResponse response = com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(jsonObject), AwsResponse.class);
		GetSmnResponse getSmnResponse = null;
		if (null != response) {
			if ("api_success".equals(response.getStatus())) {
				String dataInfoString = JsonUtils.toJsonString(response.getResponse());
				getSmnResponse = JsonUtils.toJavaObject(dataInfoString, GetSmnResponse.class);
			}
		}
		if (null != getSmnResponse) {
			if (null != getSmnResponse.getDataArea()) {
				if (CollectionUtils.isNotEmpty(getSmnResponse.getDataArea().getEngines())) {
					return getSmnResponse.getDataArea().getEngines().get(0).getServiceModelName();
				}
				return null;
			}
		}
		return null;
	}


	public String getseThreadbyUserId() {
		UserT kfz = loginDao.getUserByUserName(KFZ);
		UserTokenT userTokenT = userTokenTMapper.selectByUserId(kfz.getId());
		return userTokenT.getIdToken();
	}

}
